package sf.database.template.sql;

import sf.tools.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class SqlHelp {
    /**
     * sql压缩
     * @param sql
     * @return
     */
    public static String compressSql(String sql) {
//        if (StringUtils.isNotBlank(sql)) {
//            sql = StringUtils.replace(sql, "\n", "").replaceAll("\\s+", " ");
//        }
        sql = replaceLineSql(sql);
        return sql;
    }

    /**
     * 快速替换压缩方法
     * @param sql
     * @return
     */
    public static String replaceLineSql(String sql) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(sql)) {
            char pre = 0;
            for (int i = 0; i < sql.length(); i++) {
                char c = sql.charAt(i);
                if (c == '\n' || c == '\r' || c == '\t') {
                    c = ' ';
                }
                if (c == ' ' && pre == ' ') {
                    continue;
                }
                pre = c;
                sb.append(c);
            }
        } else {
            return sql;
        }
        return sb.toString();
    }

    /**
     * 本方法会去掉换行符
     * @param list
     * @return
     */
    public static Map<String, String> fromMarkdown(List<String> list) {
        Map<String, String> map = new HashMap<>();
        StringBuilder value = new StringBuilder();
        String currentKey = "";
        for (int i = 0; i < list.size(); i++) {
            String line = list.get(i);
            if (i + 1 < list.size() && list.get(i + 1).startsWith("===")) {
                continue;
            }
            if (line.startsWith("===")) {
                if (StringUtils.isNotBlank(currentKey)) {
                    map.put(currentKey, value.toString());
                    value.delete(0, value.length());
                }
                currentKey = list.get(i - 1);
                continue;
            }
            line = line.trim();
            if (!line.startsWith("*") && (i + 2 >= list.size() || !list.get(i + 2).startsWith("==="))) {//+2为忽略下一个 === 之前的模板名称
                if (!line.startsWith("--")) {
                    if (line.contains("--")) {
                        line = line.substring(0, line.indexOf("--"));
                        line = line.trim();
                    }
                    if (StringUtils.isNotBlank(line)) {
                        value.append(value.length() > 0 ? " " : "").append(line);
                    }
                }
            }
        }
        if (value.length() > 0) {
            map.put(currentKey, value.toString());
        }
        return map;
    }


}
